package com.yupi.yuoj.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yuoj.annotation.AuthCheck;
import com.yupi.yuoj.common.BaseResponse;
import com.yupi.yuoj.common.DeleteRequest;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.common.ResultUtils;
import com.yupi.yuoj.constant.UserConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.dto.membershiporder.MembershipOrderAddRequest;
import com.yupi.yuoj.model.dto.membershiporder.MembershipOrderQueryRequest;
import com.yupi.yuoj.model.entity.MembershipOrder;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.MembershipOrderVO;
import com.yupi.yuoj.service.MembershipOrderService;
import com.yupi.yuoj.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 会员订单接口
 *
 * @author jingjin
 */
@RestController
@RequestMapping("/membership_order")
@Slf4j
public class MembershipOrderController {

    @Resource
    private MembershipOrderService membershipOrderService;

    @Resource
    private UserService userService;

    /**
     * 创建会员订单
     *
     * @param membershipOrderAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addMembershipOrder(@RequestBody MembershipOrderAddRequest membershipOrderAddRequest, HttpServletRequest request) {
        if (membershipOrderAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MembershipOrder membershipOrder = new MembershipOrder();
        BeanUtils.copyProperties(membershipOrderAddRequest, membershipOrder);
        membershipOrderService.validMembershipOrder(membershipOrder, true);
        User loginUser = userService.getLoginUser(request);
        membershipOrder.setUserId(loginUser.getId());
        boolean result = membershipOrderService.save(membershipOrder);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newMembershipOrderId = membershipOrder.getId();
        return ResultUtils.success(newMembershipOrderId);
    }

    /**
     * 删除会员订单
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteMembershipOrder(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        MembershipOrder oldMembershipOrder = membershipOrderService.getById(id);
        ThrowUtils.throwIf(oldMembershipOrder == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldMembershipOrder.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = membershipOrderService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<MembershipOrder> getMembershipOrderById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MembershipOrder membershipOrder = membershipOrderService.getById(id);
        if (membershipOrder == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(membershipOrder);
    }

    /**
     * 分页获取会员订单列表（仅管理员）
     *
     * @param membershipOrderQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<MembershipOrder>> listMembershipOrderByPage(@RequestBody MembershipOrderQueryRequest membershipOrderQueryRequest) {
        long current = membershipOrderQueryRequest.getCurrent();
        long size = membershipOrderQueryRequest.getPageSize();
        Page<MembershipOrder> membershipOrderPage = membershipOrderService.page(new Page<>(current, size),
                membershipOrderService.getQueryWrapper(membershipOrderQueryRequest));
        return ResultUtils.success(membershipOrderPage);
    }

    /**
     * 分页获取会员订单列表（封装类）
     *
     * @param membershipOrderQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<MembershipOrderVO>> listMembershipOrderVOByPage(@RequestBody MembershipOrderQueryRequest membershipOrderQueryRequest,
            HttpServletRequest request) {
        long current = membershipOrderQueryRequest.getCurrent();
        long size = membershipOrderQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<MembershipOrder> membershipOrderPage = membershipOrderService.page(new Page<>(current, size),
                membershipOrderService.getQueryWrapper(membershipOrderQueryRequest));
        return ResultUtils.success(membershipOrderService.getMembershipOrderVOPage(membershipOrderPage, request));
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<MembershipOrderVO> getMembershipOrderVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        MembershipOrder membershipOrder = membershipOrderService.getById(id);
        if (membershipOrder == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(membershipOrderService.getMembershipOrderVO(membershipOrder, request));
    }

    /**
     * 分页获取当前用户的会员订单列表
     *
     * @param membershipOrderQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<MembershipOrderVO>> listMyMembershipOrderVOByPage(@RequestBody MembershipOrderQueryRequest membershipOrderQueryRequest,
            HttpServletRequest request) {
        if (membershipOrderQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        membershipOrderQueryRequest.setUserId(loginUser.getId());
        long current = membershipOrderQueryRequest.getCurrent();
        long size = membershipOrderQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<MembershipOrder> membershipOrderPage = membershipOrderService.page(new Page<>(current, size),
                membershipOrderService.getQueryWrapper(membershipOrderQueryRequest));
        return ResultUtils.success(membershipOrderService.getMembershipOrderVOPage(membershipOrderPage, request));
    }

}